package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import util.HibernateUtil;
import view.SearchBookPage;
import bean.Catalog;
import dto.BookDTO;

public class DeleteBookController {

	private EditBookController editController;

	class DeleteBookListener implements ActionListener {
		private SearchBookPage searchBook;

		DeleteBookListener(SearchBookPage searchBook) {
			this.searchBook = searchBook;
		}

		public void actionPerformed(ActionEvent arg0) {
			int index = Integer.parseInt(arg0.getActionCommand());
			BookDTO selectedBookToDelete = searchBook.getSearchedBooks().get(
					index);

			String bookCatalog = "[" + selectedBookToDelete.getDeweyDecimalNo()
					+ "]" + selectedBookToDelete.getTitle();
			int choice = searchBook.showConfirmDialog(bookCatalog);

			if (choice == 0) {
				deleteBookInDB(selectedBookToDelete);

				searchBook.getSearchedBooks().remove(selectedBookToDelete);

				searchBook.reDrawThis(new ActionListener() {

					public void actionPerformed(ActionEvent arg0) {
						int index = Integer.parseInt(arg0.getActionCommand());
						editController.editBook(searchBook.getLogonDTO(),
								searchBook.getSearchedBooks().get(index));
					}
				}, new DeleteBookListener(searchBook));
				searchBook.displayMessage(bookCatalog + " deleted.");
			}
		}
	}

	private void deleteBookInDB(BookDTO bookDTO) {

		Catalog catalogBean = null;

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction;

		Query query = session
				.createQuery(" FROM Catalog WHERE deweyDecimalNo = '"
						+ bookDTO.getDeweyDecimalNo() + "'");

		if (!query.list().isEmpty()) {
			catalogBean = (Catalog) query.list().get(0);

			transaction = session.beginTransaction();
			session.delete(catalogBean);
			transaction.commit();
		}
	}
}
